<!DOCTYPE html>
<html>
<head>
    <title>🌐 CORS 跨域调用测试</title>
    <meta charset="utf-8">
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 50px auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        button {
            background: #28a745;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
        }
        button:hover {
            background: #218838;
        }
        button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 4px;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        .endpoint {
            background: #f8f9fa;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
            font-family: monospace;
        }
        .status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
        .status.online {
            background: #d4edda;
            color: #155724;
        }
        .status.offline {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🌐 CORS 跨域调用测试</h1>
        <p>此页面用于测试Express TypeScript API的跨域访问功能</p>
        <p><strong>API地址:</strong> <span id="api-url">http://localhost:3379</span> 
           <span id="status" class="status offline">离线</span></p>

        <div class="endpoint">
            <strong>📍 可用端点:</strong><br>
            • GET /health - 健康检查<br>
            • GET /api/payments/config - Stripe配置<br>
            • POST /api/payments/payment-intent - 创建支付意图<br>
            • GET /api/users - 用户列表<br>
            • GET /api/posts - 文章列表
        </div>

        <h3>🧪 测试操作</h3>
        <button onclick="testHealth()">🏥 测试健康检查</button>
        <button onclick="testStripeConfig()">💳 测试Stripe配置</button>
        <button onclick="testCorsHeaders()">📋 检查CORS头</button>
        <button onclick="testPaymentIntent()">💰 测试创建支付意图</button>
        <button onclick="clearResults()">🗑️ 清空结果</button>

        <div id="result" class="result info">
点击上方按钮开始测试...

⚠️ 注意事项:
1. 确保后端服务运行在 http://localhost:3379
2. 如果看到CORS错误，说明配置有问题
3. 成功的响应表明跨域访问正常工作
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:3379';
        let resultDiv = document.getElementById('result');
        let statusSpan = document.getElementById('status');

        // 检查API状态
        async function checkApiStatus() {
            try {
                const response = await fetch(`${API_BASE}/health`);
                if (response.ok) {
                    statusSpan.textContent = '在线';
                    statusSpan.className = 'status online';
                } else {
                    statusSpan.textContent = '错误';
                    statusSpan.className = 'status offline';
                }
            } catch (error) {
                statusSpan.textContent = '离线';
                statusSpan.className = 'status offline';
            }
        }

        // 页面加载时检查状态
        checkApiStatus();
        setInterval(checkApiStatus, 5000); // 每5秒检查一次

        function showResult(content, type = 'info') {
            resultDiv.className = `result ${type}`;
            resultDiv.textContent = content;
        }

        function appendResult(content) {
            resultDiv.textContent += '\n' + content;
        }

        async function testHealth() {
            showResult('🏥 正在测试健康检查...', 'info');
            
            try {
                const startTime = Date.now();
                const response = await fetch(`${API_BASE}/health`);
                const endTime = Date.now();
                const data = await response.json();
                
                const result = `✅ 健康检查成功！

📊 响应信息:
• 状态码: ${response.status} ${response.statusText}
• 响应时间: ${endTime - startTime}ms
• 服务器状态: ${data.status}
• 环境: ${data.environment}
• 数据库: ${data.database}

🌐 CORS 头:
• Access-Control-Allow-Origin: ${response.headers.get('Access-Control-Allow-Origin')}

📄 完整响应:
${JSON.stringify(data, null, 2)}`;
                
                showResult(result, 'success');
            } catch (error) {
                showResult(`❌ 健康检查失败!\n\n错误信息: ${error.message}\n\n可能的原因:\n1. 后端服务未启动\n2. 端口3001被占用\n3. 网络连接问题`, 'error');
            }
        }

        async function testStripeConfig() {
            showResult('💳 正在测试Stripe配置...', 'info');
            
            try {
                const response = await fetch(`${API_BASE}/api/payments/config`);
                const data = await response.json();
                
                const result = `✅ Stripe配置获取成功！

📊 响应信息:
• 状态码: ${response.status} ${response.statusText}
• 成功: ${data.success}

🌐 CORS 头:
• Access-Control-Allow-Origin: ${response.headers.get('Access-Control-Allow-Origin')}

📄 配置信息:
${JSON.stringify(data, null, 2)}`;
                
                showResult(result, 'success');
            } catch (error) {
                showResult(`❌ Stripe配置获取失败!\n\n错误信息: ${error.message}`, 'error');
            }
        }

        async function testCorsHeaders() {
            showResult('📋 正在检查CORS头...', 'info');
            
            try {
                // 发送预检请求
                const response = await fetch(`${API_BASE}/api/payments/payment-intent`, {
                    method: 'OPTIONS',
                    headers: {
                        'Origin': window.location.origin,
                        'Access-Control-Request-Method': 'POST',
                        'Access-Control-Request-Headers': 'Content-Type'
                    }
                });
                
                const result = `✅ CORS预检请求成功！

📊 响应信息:
• 状态码: ${response.status} ${response.statusText}

🌐 重要的CORS头:
• Access-Control-Allow-Origin: ${response.headers.get('Access-Control-Allow-Origin') || '未设置'}
• Access-Control-Allow-Methods: ${response.headers.get('Access-Control-Allow-Methods') || '未设置'}
• Access-Control-Allow-Headers: ${response.headers.get('Access-Control-Allow-Headers') || '未设置'}

✅ CORS配置验证:
${response.headers.get('Access-Control-Allow-Origin') === '*' ? '✓ 允许所有来源访问' : '⚠️ 限制特定来源'}
${response.headers.get('Access-Control-Allow-Methods')?.includes('POST') ? '✓ 允许POST请求' : '⚠️ 不允许POST请求'}
${response.headers.get('Access-Control-Allow-Headers')?.includes('Content-Type') ? '✓ 允许Content-Type头' : '⚠️ 不允许Content-Type头'}`;
                
                showResult(result, 'success');
            } catch (error) {
                showResult(`❌ CORS检查失败!\n\n错误信息: ${error.message}`, 'error');
            }
        }

        async function testPaymentIntent() {
            showResult('💰 正在测试创建支付意图...', 'info');
            
            try {
                const response = await fetch(`${API_BASE}/api/payments/payment-intent`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        userId: '2',
                        amount: 1000,
                        currency: 'usd',
                        description: 'CORS测试支付',
                        allowRedirects: false
                    })
                });
                
                const data = await response.json();
                
                const result = `✅ 支付意图创建${data.success ? '成功' : '失败'}！

📊 响应信息:
• 状态码: ${response.status} ${response.statusText}
• 成功: ${data.success}
• 消息: ${data.message}

🌐 CORS 头:
• Access-Control-Allow-Origin: ${response.headers.get('Access-Control-Allow-Origin')}

📄 支付信息:
${JSON.stringify(data, null, 2)}

🎉 跨域POST请求成功！这证明您的API完全支持跨域访问。`;
                
                showResult(result, data.success ? 'success' : 'error');
            } catch (error) {
                showResult(`❌ 支付意图创建失败!\n\n错误信息: ${error.message}\n\n这可能是CORS配置问题或后端错误。`, 'error');
            }
        }

        function clearResults() {
            showResult('结果已清空。点击上方按钮开始新的测试...', 'info');
        }

        // 显示当前页面来源信息
        window.addEventListener('load', () => {
            const origin = window.location.origin;
            const protocol = window.location.protocol;
            
            if (protocol === 'file:') {
                document.getElementById('api-url').innerHTML += ' <span style="color: #856404;">(从本地文件访问)</span>';
            } else {
                document.getElementById('api-url').innerHTML += ` <span style="color: #0c5460;">(从 ${origin} 访问)</span>`;
            }
        });
    </script>
</body>
</html> 